package com.xwj.redpacket.controller;

import com.xwj.common.dto.BaseResponse;
import com.xwj.common.enums.StatusCode;
import com.xwj.redpacket.dto.RedPacketDto;
import com.xwj.redpacket.service.RedPacketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;

/**
 * @author xwj
 * @date 2020/4/27
 */
@RestController
@RequestMapping("/red/packet")
public class RedPacketController {
    @Autowired
    private RedPacketService redPacketService;

    /**
     * 发红包
     *
     * @param redPacketDto
     * @param bindingResult
     * @return
     */
    @GetMapping("/send")
    public BaseResponse sendRedPacket(@Valid RedPacketDto redPacketDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new BaseResponse(StatusCode.INVALID_PARAM);
        }
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        String redPacket = redPacketService.sendRedPacket(redPacketDto);
        response.setData(redPacket);
        return response;
    }

    /**
     * 抢红包
     *
     * @param userId 用户id
     * @param redId  红包标识
     * @return
     */
    @GetMapping("/rob")
    public BaseResponse robRedPacket(Long userId, String redId) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        BigDecimal result = redPacketService.robRedPacket(userId, redId);
        if(result != null) {
            response.setData(result);
        } else {
            response.setMsg("红包已抢完");
        }
        return response;
    }
}
